﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using spUtils;
using spData.Common;
using spMapping;

namespace spWeb.Page.XZ
{
    public partial class zx_Gsspsl : TaskPage
    {
        #region Property
        public string isCssShow
        {
            get { return ViewState["isCssShow"] == null ? "" : (string)ViewState["isCssShow"]; }
            set { ViewState["isCssShow"] = value; }
        }
        public List<dc_xz_Gsspsl_Details> details
        {
            get { return ViewState["details"] == null ? new List<dc_xz_Gsspsl_Details>() : ViewState["details"] as List<dc_xz_Gsspsl_Details>; }
            set { ViewState["details"] = value; }
        }

        public string CompanyCategoryText
        {
            get
            {
                return CompanyCategory.SelectedItem != null ? CompanyCategory.SelectedItem.Text : string.Empty;
            }
        }

        public bool IsLoad
        {
            get
            {
                return CompanyCategoryText.Equals(string.Empty);
            }
        }

        public bool IsBranch
        {
            get
            {
                return CompanyCategoryText.Contains(GsspslConstants.BranchCompany);
            }
        }

        #endregion

        #region Method Init Controls Value & Show/Hide & Enable/Disable & Opinion
        private void InitControls()
        {
            #region Init controls value
            //db.bind
            Expression exp = new Expression();
            string did = Request.QueryString["DID"];
            exp = string.IsNullOrEmpty(did) ? dc_xz_Gsspsl.process == TaskAPI.Process & dc_xz_Gsspsl.incident == TaskAPI.Incident : dc_xz_Gsspsl.id == did;
            if (TaskAPI.IsInitiate)
            {
                exp &= dc_xz_Gsspsl.userName == USER.UserName;
            }

            dc_xz_Gsspsl v = exp.ListFirst<dc_xz_Gsspsl>();
            if (v != null)
            {
                SetControlsValue(v);
                DepEName.Text = v.Department;
                //DID方式加载
                if (!string.IsNullOrEmpty(did))
                {
                    TaskAPI.LoadByDID(v.Process, v.Incident);
                    Process = v.Process;
                    Incident = v.Incident;
                }
            }
            else
            {
                UserFullName.Text = USER.UserFullName;
                Time.Text = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                Department.Text = USER.Department;
                DepEName.Text = USER.DepEName;
                Tel.Text = USER.EXTEND.CellPhone;
            }

            BindDetails();
            CollectKjkm();
            PushKjkm();

            #endregion

            #region Init Show/Hide、Enable/Disable
            bool flg = TaskAPI.IsBeginStep && TaskAPI.IsAllowSubmit;
            CompanyCategory_SelectedIndexChanged(null, null);
            //SetEnable(flg, Subject, City, SetReason, Company, Company1, Company2, SetReason, CompanyCategory, pl_NonSub, RunRange, pl_SubCompany, pl_Company);
            //SetVisible(flg, R_Subject, R_City, R_SetReason, R_CompanyType, R_CompanyCategory, R_RegisterFund, R_ActualReceiveFund,
            //   R_PayPlan, R_RunRange, R_BusinessDeadline, R_Address, R_LegalRepresentative, R_BoardofRegentsMember
            //    , R_SupervisoryBoardMember, R_Manager, R_RunAddress, R_PersoninCharge, detailsAdd, detailsDel);
            //SetVisible 
            #endregion
        }
        #endregion

        #region Method Data Validation
        private List<string> DataValidation()
        {
            List<Regular> regs = new List<Regular>();
            if (!AssExt.IsConferWithBack && !AssExt.IsForwardWithBack)
            {
                if (TaskAPI.IsBeginStep)
                {
                    regs.Add(new Regular(RegularExp.NotEmpty, Subject.Text, "“事项主题”为必填项!"));
                    regs.Add(new Regular(RegularExp.NotEmpty, City.Text, "“城市”为必填项!"));
                    regs.Add(new Regular(RegularExp.NotEmpty, SetReason.Text, "“设立原因”为必填项!"));
                    regs.Add(new Regular(RegularExp.NotEmpty, CompanyType.Text, "“公司类别”为必填项!"));
                    regs.Add(new Regular(RegularExp.NotEmpty, RunRange.Text, "“经营范围”为必填项!"));
                    if (IsBranch)
                    {
                        regs.Add(new Regular(RegularExp.NotEmpty, RunAddress.Text, "“营业场所”为必填项!"));
                        regs.Add(new Regular(RegularExp.NotEmpty, PersoninCharge.Text, "“负责人”为必填项!"));
                    }
                    else
                    {
                        regs.Add(new Regular(RegularExp.NotEmpty, CompanyType.Text, "“公司类型”为必填项!"));
                        regs.Add(new Regular(RegularExp.NotEmpty, RegisterFund.Text, "“注册资本”为必填项!"));
                        regs.Add(new Regular(RegularExp.NotEmpty, ActualReceiveFund.Text, "“实收资本”为必填项!"));
                        regs.Add(new Regular(RegularExp.NotEmpty, PayPlan.Text, "“出资计划”为必填项!"));
                        regs.Add(new Regular(RegularExp.NotEmpty, BusinessDeadline.Text, "“营业期限”为必填项!"));
                        regs.Add(new Regular(RegularExp.NotEmpty, Address.Text, "“住所”为必填项!"));
                        regs.Add(new Regular(RegularExp.NotEmpty, LegalRepresentative.Text, "“法定代表人”为必填项!"));
                        regs.Add(new Regular(RegularExp.NotEmpty, BoardofRegentsMember.Text, "“董事会成员/执行董事”为必填项!"));
                        regs.Add(new Regular(RegularExp.NotEmpty, SupervisoryBoardMember.Text, "“监事会成员/监事”为必填项!"));
                        regs.Add(new Regular(RegularExp.NotEmpty, Manager.Text, "“经理”为必填项!"));
                    }
                    foreach (dc_xz_Gsspsl_Details v in details)
                    {
                        if (v!=null && !String.IsNullOrEmpty(v.PayRate))
                        {
                            regs.Add(new Regular(RegularExp.NotEmpty,string.IsNullOrEmpty(v.StockHolder)||string.IsNullOrEmpty(v.PayWay)||string.IsNullOrEmpty(v.PayPrice)||string.IsNullOrEmpty(v.PayRate)? "":"!",string.Format( "第{0}行“明细行信息”为必填项!",v.No)));
                            break;
                        }
                        else
                        {
                            regs.Add(new Regular(RegularExp.NotEmpty,"", "“明细行”为必填项!"));
                            break;
                        }
                       
                    }

                }
            }
            return Validation(regs);
        }
        #endregion

        #region Method Engine Transfer Value
        private void EngineTransferValue()
        {
            if (TaskAPI.IsBeginStep)
            {
                TaskAPI.Summary = Subject.Text;
            }
            TaskAPI["e_Approve"] = AssExt.Assessment.Opinion;
        }

        #endregion

        #region Method Submit
        private bool Submit(bool IsSend)
        {
            
            #region “开始”步骤
            if (TaskAPI.IsBeginStep)
            {
                dc_xz_Gsspsl v = (dc_xz_Gsspsl.process == TaskAPI.Process & dc_xz_Gsspsl.incident == TaskAPI.Incident
                                & dc_xz_Gsspsl.userName == (TaskAPI.IsInitiate ? USER.UserName : TaskAPI.UserName)).ListFirst<dc_xz_Gsspsl>();
                bool result = GetControlsValue<dc_xz_Gsspsl>(ref v);
                if (result)
                {
                    v.Process = TaskAPI.Process;
                    v.Incident = TaskAPI.Incident;
                    v.UserName = USER.UserName;
                    v.UserFullName = USER.UserFullName;
                    v.Time = System.DateTime.Now;
                    ApplicationNo.Text = GetNewSequence("DCHT-MZBHT-" + DateTime.Now.ToString("yyyyMMdd") + "-", "", 3);
                    v.ApplicationNo = ApplicationNo.Text;
                }
                ORM.Save(v);

                (dc_xz_Gsspsl_Details.process == TaskAPI.Process & dc_xz_Gsspsl_Details.incident == TaskAPI.Incident & dc_xz_Gsspsl_Details.userName == USER.UserName).Edit<dc_xz_Gsspsl_Details>(o => o.Status = 0);

                CollectKjkm();
                //loop for save
                foreach (dc_xz_Gsspsl_Details detail in details)
                {
                    if (string.IsNullOrEmpty(detail.StockHolder) || string.IsNullOrEmpty(detail.PayWay) || string.IsNullOrEmpty(detail.PayPrice) || string.IsNullOrEmpty(detail.PayRate))
                    {
                        continue;
                    }
                    detail.Process = TaskAPI.Process;
                    detail.Incident = TaskAPI.Incident;
                    detail.UserName = USER.UserName;
                    detail.Time = System.DateTime.Now;
                    detail.Status = 1;
                    ORM.Save(detail);
                }

            }
            #endregion


            if (IsSend)
            {
                EngineTransferValue();
                ORM.Save(AssExt.Assessment);
                TaskAPI.Send();
            }

            if (IsSend && TaskAPI.IsInitiate)
            {
                (dc_xz_Gsspsl.process == TaskAPI.Process & dc_xz_Gsspsl.incident == 0 & dc_xz_Gsspsl.userName == USER.UserName).Edit<dc_xz_Gsspsl>(p => p.Incident = TaskAPI.Incident);
                (dc_xz_Gsspsl_Details.process == TaskAPI.Process & dc_xz_Gsspsl_Details.incident == 0 & dc_xz_Gsspsl_Details.userName == USER.UserName).Edit<dc_xz_Gsspsl_Details>(p => { p.Incident = TaskAPI.Incident; });
            }

            //退出
            if (IsSend)
            {
                Exit();
            }
            return true;
        }
        #endregion

        #region Event Page
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                InitControls();
            }
        }
        #endregion

        #region Event Button Click

        #region Event Save As Draft
        protected void SaveAsDraft_Click(object sender, EventArgs e)
        {
            bool success = Submit(false);
            Anthem.Manager.AddScriptForClientSideEval(string.Format("JSInfomation('{0}')", success ? "保存成功!" : "保存失败!"));
        }
        #endregion

        #region Event Send
        protected void Send_Click(object sender, EventArgs e)
        {
            CollectKjkm();
            List<string> msg = DataValidation();
            if (msg.Count > 0)
            {
                Anthem.Manager.AddScriptForClientSideEval(Alert(msg));
                return;
            }
            bool success = Submit(true);
            (sender as spWeb.Controls.AssessmentExt).Refresh();
            Anthem.Manager.AddScriptForClientSideEval(string.Format("JSInfomation('{0}');{1}", success ? "提交成功!" : "提交失败!", success ? "window.close();" : ""));
        }
        #endregion

        #region Event Aborted
        protected void Aborted_Click(object sender, EventArgs e)
        {
            (dc_xz_Gsspsl.process == TaskAPI.Process & dc_xz_Gsspsl.incident == TaskAPI.Incident).Edit<dc_xz_Gsspsl>(p => { p.Status = 4; });
        }
        #endregion

        #endregion

        #region Details Bind & Add, Delete & CollectKjkm, PushKjkm

        #region Method BindDetails
        private void BindDetails()
        {
            Expression exp = (dc_xz_Gsspsl_Details.process == TaskAPI.Process & dc_xz_Gsspsl_Details.incident == TaskAPI.Incident & dc_xz_Gsspsl_Details.status == 1);

            details = exp.List<dc_xz_Gsspsl_Details>(new Region(0, 100), dc_xz_Gsspsl_Details.id.Asc) as List<dc_xz_Gsspsl_Details>;
            if (details.Count == 0 & TaskAPI.IsBeginStep)
            {
                for (int i = 0; i < 3; i++)
                {
                    details.Add(new dc_xz_Gsspsl_Details());
                }
            }
            Details.DataSource = details;
            Details.DataBind();
        }

        protected void Details_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            //null
        }

        #endregion

        #region Event Row Add, Delete
        protected void AddDelete_Click(object sender, EventArgs e)
        {
            //收集数据
            CollectKjkm();
            
            if ((sender as Anthem.Button).ID == "detailsDel")
            {
                foreach (RepeaterItem ri in Details.Items)
                {
                    Anthem.CheckBox current = ri.FindControl("Cb_XZ") as Anthem.CheckBox;
                    if (current.Checked)
                    {
                        int index = spWeb.CommHelper.ConvertToInt(current.Attributes["alt"]);
                        if (index != 0)
                        {
                            for (int i = 0; i < details.Count; i++)
                            {
                                if (details[i].No == index)
                                {
                                    details.RemoveAt(i);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                //验证是否填写注册资金
                if (string.IsNullOrEmpty(RegisterFund.Text.Trim()))
                {
                    List<Regular> regs = new List<Regular>();
                    regs.Add(new Regular(RegularExp.NotEmpty, RegisterFund.Text, "“注册资本”为必填项!"));
                    List<string> msg = Validation(regs);
                    Anthem.Manager.AddScriptForClientSideEval(Alert(msg));
                    return;
                }
                details.Add(new dc_xz_Gsspsl_Details());
            }

            //重新编号、绑定
            for (int i = 0; i < details.Count; i++)
            {
                details[i].No = i;
            }
            Details.DataSource = details;
            Details.DataBind();

            PushKjkm();
        }

        #endregion

        #region Method CollectKjkm, PushKjkm
        protected void CollectKjkm()
        {
            int i = 0;
            foreach (RepeaterItem ri in Details.Items)
            {
                Anthem.TextBox StockHolder = ri.FindControl("StockHolder") as Anthem.TextBox;
                Anthem.TextBox PayWay = ri.FindControl("PayWay") as Anthem.TextBox;
                Anthem.TextBox PayPrice = ri.FindControl("PayPrice") as Anthem.TextBox;
                Anthem.TextBox PayRate = ri.FindControl("PayRate") as Anthem.TextBox;
                details[i].StockHolder = StockHolder.Text;
                details[i].PayWay = PayWay.Text;
                details[i].PayPrice = PayPrice.Text;
                details[i].PayRate = PayRate.Text;
                i++;
            }
            details = details;
        }

        protected void PushKjkm()
        {
            int i = 0;
            bool isModify = TaskAPI.IsBeginStep && TaskAPI.IsAllowSubmit;
            foreach (RepeaterItem ri in Details.Items)
            {
                Anthem.TextBox StockHolder = ri.FindControl("StockHolder") as Anthem.TextBox;
                Anthem.TextBox PayWay      = ri.FindControl("PayWay") as Anthem.TextBox;
                Anthem.TextBox PayPrice    = ri.FindControl("PayPrice") as Anthem.TextBox;
                Anthem.TextBox PayRate     = ri.FindControl("PayRate") as Anthem.TextBox;
                StockHolder.Text = details[i].StockHolder;
                PayWay.Text = details[i].PayWay;
                PayPrice.Text = details[i].PayPrice;
                PayRate.Text = details[i].PayRate;  
                isCssShow = isModify ? "" : "display:none;";
                i++;
            }
        }
        #endregion

        protected void CompanyCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetVisible(false, pl_SubCompany, pl_NonSub, pl_Company);
            SetVisible(!IsLoad && IsBranch, pl_SubCompany);
            SetVisible(!IsLoad && !IsBranch, pl_NonSub, pl_Company);
        }

        protected void PayPrice_TextChanged(object sender, EventArgs e)
        {
            Anthem.TextBox tb = sender as Anthem.TextBox;
            Anthem.TextBox tbRate = tb.Parent.FindControl("PayRate") as Anthem.TextBox;
            float total = spWeb.CommHelper.ConvertToFloat(RegisterFund.Text);
            if (tbRate != null&&total!=0)
                tbRate.Text = (spWeb.CommHelper.ConvertToFloat(tb.Text) * 100 / total).ToString("F2");
        }

        protected void RegisterFund_TextChanged(object sender, EventArgs e)
        {
            foreach (RepeaterItem ri in Details.Items)
            {
                Anthem.TextBox PayPrice = ri.FindControl("PayPrice") as Anthem.TextBox;
                Anthem.TextBox PayRate = ri.FindControl("PayRate") as Anthem.TextBox;
                float total = spWeb.CommHelper.ConvertToFloat(RegisterFund.Text);
                if (PayRate != null && total != 0)
                    PayRate.Text = (spWeb.CommHelper.ConvertToFloat(PayPrice.Text) * 100 / total).ToString("F2");
            }
        }

        #endregion
    }
    #region GsspslConstants
    public class GsspslConstants
    {
        public const string BranchCompany = "分公司";
    }
    #endregion
    
}